import URL from 'url';
import Path from 'path-browserify';
import config from '@/config/index.js'
import tools from '@/utils/tools/index.js'
import { notLoginToast } from '@/utils/request/utils.js'

/**
 * @desc 获取static文件URL
 * @param {Object} filePath 文件路径
 * @return {String}
 */
function getStaticUrl(filePath) {
	return URL.resolve(config['fileURL'], '/static' + filePath);
}

/**
 * @desc 获取文件地址
 * @param {String} filePath 文件路径
 * @return {String}
 */
function getFileUrl(filePath) {
	if (uni.$uv.test.url(filePath)) {
		return filePath
	} else if (uni.$uv.test.string(filePath)) {
		return URL.resolve(config['fileURL'], filePath)
	}
	return;
}

/**
 * @desc 获取多个文件地址
 * @param data {Array} 数据
 * @param w {Number} 图片尺寸
 * @return {Array}
 */
function getFileUrls(data, w) {
	if (uni.$uv.test.array(data)) {
		return data.map(item => getFileUrl(item, w));
	}
	return [];
}

/**
 * @desc 上传文件
 * @param files {Array} 文件信息
 * @returns{Promise<Object>}
 */
async function uploadFile(filePath) {
	return new Promise(async (resolve, reject) => {
		uni.uploadFile({
			url: config['baseURL'] + '/public/upload/file',
			timeout: 1000 * 30,
			filePath,
			name: 'file',
			header: {
				'Authorization': uni.getStorageSync('token'),
			},
			async success(res) {
				let data = res['data'];
				uni.$uv.test.jsonString(data) && (data = JSON.parse(res['data']));
				switch (data['code']) {
					case 200:
						resolve(data);
						break;
					case 210:
						notLoginToast();
						reject(data);
						break;
					case 220:
						uni.hideLoading();
						tools.toast({ title: data['err'] || '请求失败' });
						reject(data);
				}
			},
			fail(err) {
				uni.showToast({ title: '请求错误！', duration: 1500, icon: 'error' });
				reject({ code: 210, err: '请求失败！' });
			}
		})

	})
}

export default {
	getStaticUrl,
	getFileUrl,
	getFileUrls,
	uploadFile
}